﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;

namespace Assets.Editor.BehaviorEditor.View
{
    public class Connection
    {
        public ConnectionPoint inPoint;
        public ConnectionPoint outPoint;
        private Action<Connection> OnClickRemoveConnection;

        public Connection(
            ConnectionPoint inPoint
            , ConnectionPoint outPoint
            , Action<Connection> onClickRemoveConnection)
        {
            this.inPoint = inPoint;
            this.outPoint = outPoint;

            inPoint.connections.Add(this);
            outPoint.connections.Add(this);

            this.OnClickRemoveConnection = onClickRemoveConnection;
        }

        public void Draw()
        {
            Vector2 startPos = outPoint.rect.center;
            Vector2 endPos = inPoint.rect.center;
            Vector2 p1Pos = GetP1Pos(outPoint, endPos);
            Vector2 p2Pos = GetP2Pos(p1Pos, endPos);

            DrawConnection(startPos, endPos, p1Pos, p2Pos);

            if (Handles.Button(p2Pos, Quaternion.identity, 4, 8, Handles.RectangleHandleCap))
            {
                if (OnClickRemoveConnection != null)
                {
                    OnClickRemoveConnection(this);
                }
            }
        }
        
        public static void DrawConnection(ConnectionPoint outPoint, Vector2 endPos)
        {
            Vector2 startPos = outPoint.rect.center;
            Vector2 p1Pos = GetP1Pos(outPoint, endPos);
            Vector2 p2Pos = GetP2Pos(p1Pos, endPos);

            DrawConnection(startPos, endPos, p1Pos, p2Pos);
        }

        private static Vector2 GetP2Pos(Vector2 p1, Vector2 endPos)
        {
            return new Vector2(p1.x, endPos.y);
        }

        private static Vector2 GetP1Pos(ConnectionPoint outPoint, Vector2 endPos)
        {
            Vector2 parentPos = outPoint.rect.center;
            List<Vector2> childPos = outPoint.connections.Select(c => c.inPoint.rect.center).ToList();

            float minDistanceX = endPos.x - parentPos.x;
            foreach (var item in childPos)
            {
                if(minDistanceX <= 10)
                {
                    return new Vector2(10 + parentPos.x, parentPos.y);
                }
                float distanceX = item.x - parentPos.x;
                if (minDistanceX > distanceX)
                {
                    minDistanceX = distanceX;
                }
            }

            return new Vector2(minDistanceX / 2 + parentPos.x, parentPos.y);
        }
        
        public static void DrawConnection(Vector2 startPos, Vector2 endPos, Vector2 p1Pos, Vector2 p2Pos)
        {
            Handles.DrawLines(new Vector3[] { startPos, p1Pos, p1Pos, p2Pos, p2Pos, endPos });
        }

    }
}
